package logic

import (
	"context"
	"course_srv/course"
	"course_srv/internal/svc"
	"course_srv/models/es"
	"course_srv/models/mysql"
	"course_srv/models/redis"
	"errors"

	"github.com/zeromicro/go-zero/core/logx"
)

type CourseAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCourseAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CourseAddLogic {
	return &CourseAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CourseAddLogic) CourseAdd(in *course.CourseAddRequest) (*course.CourseAddResponse, error) {

	c := mysql.Course{
		Name:    in.Name,
		Teacher: in.Teacher,
		Intro:   in.Intro,
		Price:   float64(in.Price),
		Cover:   in.Cover,
		Video:   in.Video,
	}
	s := mysql.Status{}
	err := s.GetStatusId()
	if err != nil {
		return nil, errors.New("查询失败")
	}
	if s.Status == 1 {
		err = c.Add()
		if err != nil {
			logx.Error("课程发布失败")
			return nil, errors.New("课程发布失败")
		}
		logx.Info("课程发布成功")
		//同步es
		es.SyncCourse(c)
		//添加到缓存中
		redis.AddCourse(c)
	}

	return &course.CourseAddResponse{Id: int32(c.ID)}, nil
}
